package com.ztom.context.support.event.multicast

import cn.hutool.core.util.ClassUtil
import com.ztom.beans.factory.BeanFactory
import com.ztom.context.support.event.event.ApplicationEvent
import com.ztom.context.support.event.listener.ApplicationListener
import java.lang.reflect.ParameterizedType
import kotlin.reflect.full.isSubclassOf

/**
 * @author ZhangTao
 */
class SimpleApplicationEventMulticaster(beanFactory: BeanFactory) : AbstractApplicationEventMulticaster() {

    init {
        setBeanFactory(beanFactory)
    }

    override fun multicastEvent(event: ApplicationEvent) {
        applicationListeners.filter { supportEvent(it, event) }.forEach { it.onApplicationEvent(event) }
    }

    private fun supportEvent(listener: ApplicationListener<ApplicationEvent>, event: ApplicationEvent): Boolean {
        val type = listener::class.java.genericInterfaces[0]
        // 获取泛型类型
        val actualType = (type as ParameterizedType).actualTypeArguments[0]
        val loadClass = ClassUtil.loadClass<Any>(actualType.typeName)
        return event::class.isSubclassOf(loadClass.kotlin)
    }
}